package org.apache.database.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Condition {
    private String sql;

    public Condition(String sql) {
        this.sql = sql;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public static class Builder{
        private List<Criterion> list;
        private Class aClass;

        public Builder() {
            list =new ArrayList<>();

        }

        public Builder where(Class aClass){
            this.aClass=aClass;
            return this;
        }
        public Builder whereEq(Serializable field,Serializable value){
            list.add(new Criterion(field,"=",value));
            return this;
        }
        public Builder whereGt(Serializable field,Serializable value){
            list.add(new Criterion(field,">",value));
            return this;
        }
        public Builder whereLt(Serializable field,Serializable value){
            list.add(new Criterion(field,"<",value));
            return this;
        }
        public Builder like(Serializable field,Serializable value){
            list.add(new Criterion(field,"like",value));
            return this;
        }
        public Builder in(Serializable fieldName,Serializable ...value){
            StringBuffer stringBuffer =new StringBuffer();
            stringBuffer.append("(");
            for (int i = 0; i < value.length; i++) {
                stringBuffer.append(value[i] instanceof String?"'"+value[i]+"'":value[i]);
                stringBuffer.append(",");
            }
            stringBuffer.deleteCharAt(stringBuffer.length()-1);
            stringBuffer.append(")");
            list.add(new Criterion(fieldName,"in",stringBuffer));
            return this;
        }

        private void check(){

        }
        public Condition builder(){
            StringBuffer stringBuffer =new StringBuffer();
            stringBuffer.append("WHERE ");
            for (Criterion criterion : list) {
                stringBuffer.append(criterion.toString());
                stringBuffer.append(" AND");
            }
            return  new Condition(stringBuffer.substring(0,stringBuffer.length()-3));
        }
    }

    public static  class  Criterion{

        private Serializable name;

        private Serializable condition;
        private Serializable value;

        public Criterion( Serializable name, Serializable condition, Serializable value) {
            this.name = name;
            this.condition = condition;

            this.value = value instanceof String?"'"+value+"'":value;
        }

        @Override
        public String toString() {

            return " "+ name+" "+condition+" "+value;
        }
    }
}
